package cn.brilliantfuture.commentry.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.apache.log4j.Logger;

/**
 * 
 * Title: Cabinet Platform
 * 
 * Author:  LiTian  
 *
 * Date: 2013-6-25
 * 
 * Description: E-MAIL发送公共类
 * 
 */
public class EMAILScheduler extends Thread{
	
	private static Logger logger = Logger.getLogger(EMAILScheduler.class);

	// 邮件发送者地址
	private static final String SENDER_EMAIL_ADDR = "cabinet@jiadi365.com";

	// 邮件发送者邮箱用户
	private static final String SMTP_USER_NAME = "cabinet@jiadi365.com";

	// 邮件发送者邮箱密码
	private static final String SMTP_PASSWORD = "cabinet0625";

	// 邮件发送者邮箱SMTP服务器
	private static final String SMTP_SERVER_NAME = "smtp.acsm.cn";

	// 传输类型
	private static final String TRANSPORT_TYPE = "smtp";
	
	private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

	// 属性
	private static Properties props;
	
	static {
		props = new Properties();
		
		// 存储发送邮件服务器的信息
		props.put("mail.smtp.host", SMTP_SERVER_NAME);

		props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
		
		props.put("mail.smtp.socketFactory.fallback", "false");

		props.put("mail.smtp.port", 994);
		
		props.put("mail.smtp.socketFactory.port", 994);
		
		// 同时通过验证
		props.put("mail.smtp.auth", "true");
	}

	private String email;
	private String title;
	private String content;
	
	public EMAILScheduler(String email, String title, String content) {
		this.email = email;
		this.title = title;
		this.content = content;
	}
	
	@Override
	public void run() {
		logger.info("Start asyn execute send E-MAIL");

		props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
		
		props.put("mail.smtp.socketFactory.fallback", "false");

		props.put("mail.smtp.port", "994");
		
		props.put("mail.smtp.socketFactory.port", "994");

		Session session = Session.getInstance(props, null);

		// 设置调试标志,要查看经过邮件服务器邮件命令，可以用该方法
		session.setDebug(false);
		
		// 由邮件会话新建一个消息对象
		MimeMessage message = new MimeMessage(session);
		
		Transport transport = null;
		
		boolean sned = false;
		
		try {
			// 设置发件人
			Address from = new InternetAddress("=?UTF-8?B?57u/6Imy5a626YCS?=<" + SENDER_EMAIL_ADDR + ">");
			message.setFrom(from);

			// 设置收件人
			Address to = new InternetAddress(email);
			
			message.setRecipient(RecipientType.TO, to);

			// 设置主题
			message.setSubject(title);
			
			//指定邮箱内容及ContentType和编码方式
			message.setContent(getContent(content), "text/html;charset=utf-8");
			
			// 设置发信时间
			message.setSentDate(new Date());
			
			// 存储邮件信息
			message.saveChanges();
			
			transport = session.getTransport(TRANSPORT_TYPE);
			
			// 要填入你的用户名和密码；
			transport.connect(SMTP_SERVER_NAME, SMTP_USER_NAME, SMTP_PASSWORD);

			// 发送邮件,其中第二个参数是所有已设好的收件人地址
			transport.sendMessage(message, message.getAllRecipients());

			logger.info("邮件发送成功!");
			
			sned = true;

		} catch (Exception e) {
			logger.error("Send mail fail!\n" + e.getMessage());
			sned = false;
		} finally {
			if (null != transport){
				try {
					transport.close();
				} catch (MessagingException e) {
					logger.error("Send mail fail!\n" + e.getMessage());
				}
			}
		}
		
		Connection conn = null;
		PreparedStatement pstm = null;
		
		try {
			conn = JDBCDataSource.getConnection();
			
			conn.setAutoCommit(false);
			
			pstm = conn.prepareStatement("insert into email_record(email, title, content, insert_time, is_send) values(?, ?, ?, now(), ?)");
			pstm.setString(1, email);
			pstm.setString(2, title);
			pstm.setString(3, content);
			pstm.setBoolean(4, sned);
			pstm.executeUpdate();
			
			conn.commit();
			conn.setAutoCommit(true);
		} catch (SQLException e) {
			logger.error("Save email record fail!\n" + e.getMessage());
			try {
				conn.rollback();
			} catch (SQLException e1) {
				logger.error("Rollback fail!\n" + e1.getMessage());
			}
		} finally {
			JDBCDataSource.closeResource(conn, pstm, null);
		}
	}
	
	private String getContent(String content){
		StringBuffer sb = new StringBuffer();
		sb.append("<html>");
		sb.append("<head>");
		sb.append("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />");
		sb.append("<style>");
		sb.append("body{ padding:0; margin:0;}");
		sb.append(".mail{ width:783px; margin:0 auto;}");
		sb.append(".top{ width:763px; height:50px; padding-left:20px; padding-top:14px; background:url(http://218.245.5.246/cabinet/mail/images/top_bg_03.jpg) repeat-x; line-height:64px; text-align:left;}");
		sb.append(".top{ width:763px; height:50px; padding-left:20px; padding-top:14px; background:url(http://218.245.5.246/cabinet/mail/images/top_bg_03.jpg) repeat-x; line-height:64px; text-align:left;}");
		sb.append(".banner{ width:783px; height:211px; margin:0 auto;}");
		sb.append(".content{ width:783px; min-height:348px; *height:348px; background:url(http://218.245.5.246/cabinet/mail/images/con_bg_14.jpg) center bottom repeat-x;}");
		sb.append(".content td{ font-family:'宋体'; font-size:14px; color:#000000; padding:0 15px; line-height:24px;}");
		sb.append(".footer{ width:783px; height:35px; line-height:35px; background:url(http://218.245.5.246/cabinet/mail/images/footer_18.jpg) repeat-x; text-align:center; font-family:'宋体'; font-size:12px; color:#ffffff;}");
		sb.append("</style>");
		sb.append("</head>");
		sb.append("<body>");
		sb.append("<div class='mail'>");
		sb.append("<div class='top'><img src='http://218.245.5.246/cabinet/mail/images/logo_06.jpg' width='289' height='39' /></div>");
		sb.append("<div class='banner'><img src='http://218.245.5.246/cabinet/mail/images/banner_11.jpg' width='783' height='211' /></div>");
		sb.append("<table class='content'>");
		sb.append("<tr><td align='left'>亲爱的会员：</td></tr>");
		sb.append("<tr><td align='left' valign='top'>&#160;&#160;&#160;&#160;&#160;&#160;");
		sb.append(content);
		sb.append("</td></tr>");
		sb.append("<tr><td align='right' style='padding:20px 30px 50px 0;''>绿色家递客服</td></tr>");
		sb.append("</table>");
		sb.append("<div class='footer'>版权所有：北京绿色家递电子商务有限公司</div>");
		sb.append("</div>");
		sb.append("</body>");
		sb.append("</html>");
		
		return sb.toString();
	}
}
